package org.domon.mybatis.sql.support;

import java.lang.reflect.Field;

import org.apache.ibatis.jdbc.SQL;
import org.domon.mybatis.annotation.Column;
import org.domon.mybatis.annotation.ID;
import org.domon.mybatis.annotation.Table;
import org.domon.mybatis.sql.DbNameGenerator;
import org.springframework.util.StringUtils;

public class AnnotationDbNameGenerator extends DefaultDbNameGenerator implements DbNameGenerator {

    public String generateInsertSql(Class<?> modelClass) {
        SQL SQL_BUILDER = new SQL();
        
        Table table = modelClass.getAnnotation(Table.class);
        if (table != null) {
            if (StringUtils.hasText(table.value())) {
                SQL_BUILDER.INSERT_INTO(table.value());
            } else {
                SQL_BUILDER.INSERT_INTO(getDbName(modelClass.getSimpleName()));
            }
            
            Field[] fields = modelClass.getDeclaredFields();
            for (Field field : fields) {
                if (field.isAnnotationPresent(Column.class)) {
                    SQL_BUILDER.VALUES(field.getAnnotation(Column.class).value(), DB_VALUE.replace("?", field.getName()));
                } else {
                    SQL_BUILDER.VALUES(getDbName(field.getName()), DB_VALUE.replace("?", field.getName()));
                }
            }
        }
        
        if (StringUtils.hasText(SQL_BUILDER.toString())) {
            return SQL_BUILDER.toString();
        }

        return super.generateInsertSql(modelClass);
    }

    @Override
    protected boolean isTableID(Field field) {
        if (field.isAnnotationPresent(ID.class)) {
            return true;
        }
        return super.isTableID(field);
    }
}
